// 重写history
function patchRouter(type: keyof History) {
  const orig = history[type];
  return function (this: unknown) {
    const e = new Event(type);
    window.dispatchEvent(e);
    // eslint-disable-next-line prefer-rest-params
    return orig.apply(this, arguments);
  };
}

history.pushState = patchRouter('pushState');
history.replaceState = patchRouter('replaceState');

export const routerChangeListener = (handler: (e: Event) => void) => {
  // 监听Hash、History路由变化
  window.addEventListener('popstate', (e) => handler(e), true);
  // AOP拦截
  window.addEventListener('replaceState', (e) => handler(e), true);
  window.addEventListener('pushState', (e) => handler(e), true);
};
